package com.auto.learning.activity;

import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler.Callback;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewTreeObserver;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.auto.learning.R;
import com.auto.learning.adapter.HomePageListViewAdapter;
import com.auto.learning.bean.AnchorBean;
import com.auto.learning.bean.BookBean;
import com.auto.learning.bean.ResponeResult;
import com.auto.learning.event.BookNumChangeEvent;
import com.auto.learning.event.CollectEvent;
import com.auto.learning.event.EventBus;
import com.auto.learning.event.Handle;
import com.auto.learning.event.LoginSuccessEvent;
import com.auto.learning.net.Cache;
import com.auto.learning.net.HttpCommonInfo;
import com.auto.learning.net.HttpRequestHelper;
import com.auto.learning.service.MusicPlayManager;
import com.auto.learning.sharesdk.tools.ShareOpUtils;
import com.auto.learning.thread.pool.Pool;
import com.auto.learning.tools.CommonMethod;
import com.auto.learning.tools.FastBlur;
import com.auto.learning.tools.TemporaryVariable;
import com.auto.learning.view.CircleImageView;
import com.auto.learning.view.PullToRefreshListView;
import com.auto.learning.view.PullToRefreshListView.OnRefreshListener;
import com.auto.learning.view.ShareView;
import com.auto.learning.view.SharedPreferencesUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.squareup.otto.Subscribe;
import com.squareup.otto.ThreadEnforcer;

public class AnchorInfoActivity extends Activity implements Callback {
	
	private int time = HttpRequestHelper.BLUR_DEFAULT_TIMES;
	
	private static final int GETDATA_SUCCESS = 1;
	private static final int GETDATA_FAIL = 2;
	
	private LinearLayout activity_base_back,activity_base_more;
	private RelativeLayout rel_top;
	private CircleImageView image_a_face;
	private ImageView image_render;
	private TextView name,tv_anchor_book_num,tv_anchor_favor_number,tv_anchor_info;
	private RatingBar rat_num;
	private View view2,view_black;
	AnchorBean anchorBean;
	private PullToRefreshListView listview_anchor_book;
	private HomePageListViewAdapter adapter;
	private ArrayList<BookBean> list = new ArrayList<BookBean>();
	private int pageIndex = 0;
	
	private View topView;
	
	private View lvProductFooter;
	private TextView lvProductFooterMore;
	private ProgressBar lvProductFooterProgress;
	private TextView lvBtn_more;
	private LinearLayout lvLinear_more;
	
	private Handle handle = new Handle(this){
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case GETDATA_SUCCESS:
				String bottom = "";
				ResponeResult result = (ResponeResult) msg.obj;
				ArrayList<BookBean> resultList = new Gson().fromJson(result.getData(), new TypeToken<ArrayList<BookBean>>() {}.getType());
				/**
				 * 把书缓存到本地
				 */
				Cache.cacheChoosePageList2Local(resultList);
				if (pageIndex == 0) {
					list.clear();
					list.addAll(resultList);
				} else {
					list.addAll(resultList);
				}
				if (resultList.size() >= 10) {
					pageIndex++;
					lvBtn_more.setVisibility(View.VISIBLE);
					lvProductFooterMore.setText(bottom);
				} else {
					bottom = getResources().getString(R.string.text_hompage_data);
					lvLinear_more.setVisibility(View.VISIBLE);
					lvProductFooterMore.setText(bottom);
					lvProductFooterProgress.setVisibility(View.GONE);
					lvBtn_more.setVisibility(View.GONE);
				}

				if (listview_anchor_book != null) {
					listview_anchor_book.onRefreshComplete();
					listview_anchor_book.setTag(0);
				}
				if (list != null && list.size() > 0) {
					adapter.notifyDataSetChanged();
				}
				break;
			case GETDATA_FAIL:
				if (listview_anchor_book != null) {
					listview_anchor_book.onRefreshComplete();
					listview_anchor_book.setTag(0);
				}
				break;
			case HttpRequestHelper.PUBLIC_LOGIN_SUCCESS:
				CommonMethod.makeNotice(AnchorInfoActivity.this, "登录成功");
				ResponeResult login_result = (ResponeResult) msg.obj;
				if(login_result != null){
					EventBus.getEventBus("login_success_refreshUI").post(login_result);
				}
				break;
			case HttpRequestHelper.PUBLIC_LOGIN_FAIL:
				CommonMethod.makeNotice(AnchorInfoActivity.this, msg.obj.toString());
				break;
			case 100:
				if (list != null) {
					for (int i = 0; i < list.size(); i++) {
						if (list.get(i).getBookId() == msg.arg1) {
							list.get(i).setIsRead(2);
							break;
						}
					}	
				}
				if (adapter != null) {
					adapter.notifyDataSetChanged();
				}
				break;
			}
		};
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.anchor_info_activity);
		initView();
		registerEvent();
		getBookList();
		TemporaryVariable.activities.push(this);
	}
	
	private void initView(){
		if (listview_anchor_book != null && listview_anchor_book.getHeaderViewsCount() > 0) {
			listview_anchor_book.removeHeaderView(topView);
		}
		if (listview_anchor_book != null && listview_anchor_book.getFooterViewsCount() > 0) {
			listview_anchor_book.removeFooterView(lvProductFooter);
		}
		lvProductFooter = getLayoutInflater().inflate(R.layout.listview_footer,null);
		lvProductFooterMore = (TextView) lvProductFooter.findViewById(R.id.listview_foot_more);
		lvProductFooterProgress = (ProgressBar) lvProductFooter.findViewById(R.id.listview_foot_progress);
		lvBtn_more = (TextView) lvProductFooter.findViewById(R.id.btn_more);
		lvLinear_more = (LinearLayout) lvProductFooter.findViewById(R.id.linear_more);
		
		
		topView = getLayoutInflater().inflate(R.layout.anchor_info_top, null);
		rel_top = (RelativeLayout) topView.findViewById(R.id.rel_top);
		image_render = (ImageView) topView.findViewById(R.id.image_render);
		view2 = topView.findViewById(R.id.text);
		view_black = topView.findViewById(R.id.view_black);
		view_black.getBackground().setAlpha(180);
		listview_anchor_book = (PullToRefreshListView) findViewById(R.id.listview_anchor_book);
		adapter = new HomePageListViewAdapter(this, list, 3);
		listview_anchor_book.setAdapter(adapter);
		listview_anchor_book.setTag("0");
		listview_anchor_book.addHeaderView(topView);
		listview_anchor_book.setOnRefreshListener(new OnRefreshListener() {

			@Override
			public void onRefresh() {
				pageIndex = 0;
				getBookList();
			}
		});
		listview_anchor_book.addFooterView(lvProductFooter);
		lvBtn_more.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				getBookList();
			}
		});
		listview_anchor_book.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				listview_anchor_book.onScrollStateChanged(view, scrollState);
				boolean scrollEnd = false;
				try {
					if (view.getPositionForView(lvProductFooter) == view.getLastVisiblePosition()
							&& !lvProductFooterMore.getText().toString().equals(getResources().getString(R.string.text_hompage_data))) {
						scrollEnd = true;
					}
				} catch (Exception e) {
					scrollEnd = false;
				}

				int lvDataState = Integer.parseInt((listview_anchor_book.getTag()
						.toString()));
				if (scrollEnd && lvDataState == 0) {
					listview_anchor_book.setTag(1);
					lvProductFooterMore.setText("加载中");
					lvProductFooterProgress.setVisibility(View.VISIBLE);
					lvLinear_more.setVisibility(View.VISIBLE);
					lvBtn_more.setVisibility(View.GONE);
					int page = listview_anchor_book.getCount() - 2; // 减去ListView的头和尾的
					getBookList();
				}
			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				listview_anchor_book.onScroll(view, firstVisibleItem,visibleItemCount, totalItemCount);
			}
		});
		activity_base_back = (LinearLayout) findViewById(R.id.activity_base_back);
		activity_base_more = (LinearLayout) findViewById(R.id.activity_base_more);
		image_a_face = (CircleImageView) topView.findViewById(R.id.image_a_face);
		rat_num = (RatingBar) topView.findViewById(R.id.rat_num);
		name = (TextView) topView.findViewById(R.id.name);
		tv_anchor_book_num = (TextView) topView.findViewById(R.id.tv_anchor_book_num);
		tv_anchor_favor_number = (TextView) topView.findViewById(R.id.tv_anchor_favor_number);
		tv_anchor_info = (TextView) topView.findViewById(R.id.tv_anchor_info);
		activity_base_back.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		
		
		Intent intent = getIntent();
		anchorBean = (AnchorBean) intent.getSerializableExtra("m_anchor_bean");
		ImageLoader.getInstance().displayImage(anchorBean.getFace(),image_a_face);
		ImageLoader.getInstance().displayImage(anchorBean.getFace(),image_render);
		name.setText(anchorBean.getName()+"");
		rat_num.setNumStars(anchorBean.getStars());
		tv_anchor_book_num.setText(anchorBean.getBookNum()+"");
		tv_anchor_favor_number.setText(anchorBean.getFavorNum()+"");
		tv_anchor_info.setText(anchorBean.getIntro()+"");
		image_render.setVisibility(View.INVISIBLE);
		handle.postDelayed(new Runnable() {
			@Override
			public void run() {
				LayoutParams layoutParams = view2.getLayoutParams();
				layoutParams.height = rel_top.getHeight() + 10;
				layoutParams.width = rel_top.getWidth();
				view2.setLayoutParams(layoutParams);
				applyBlur();
				image_render.setVisibility(View.INVISIBLE);
			}
		},100);
		activity_base_more.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if (anchorBean != null && anchorBean.getId() > 0) {
					String url = HttpCommonInfo.MURL +"anchor-share?anchorId=" + anchorBean.getId();
					String content = anchorBean.getIntro();
					String title = "主播 "+anchorBean.getName() + " 的个人主页";
					new ShareView(AnchorInfoActivity.this, AnchorInfoActivity.this).setTitle(title).setUrl(url).setContent(content).setImageUrl(anchorBean.getFace()).setType(5).setId(anchorBean.getId()+"").show(findViewById(R.id.main_view));
				}
			}
		});
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, final Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == 100 && resultCode == 203 && data != null) {
			Pool.getPool().execute(new Runnable() {
				@Override
				public void run() {
					HttpRequestHelper.login2(AnchorInfoActivity.this,data.getStringExtra("userId"), data.getStringExtra("nickName"),
							data.getStringExtra("headImgUrl"), data.getBooleanExtra("isweixin",false), handle);
				}
			});
		}else if (requestCode == 100 && resultCode == 204) {
			EventBus.getEventBus("login_refreshUI").post(new LoginSuccessEvent());
		}
	}
	
	
	@Override
	protected void onDestroy() {
		TemporaryVariable.activities.removeElement(this);
		unRegisterEvent();
		super.onDestroy();
	}
	
	@Subscribe
	public void onEventCollect(CollectEvent event){
		if (list != null && list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				if (event.getBookId() == list.get(i).getBookId()) {
					list.get(i).setIsFavor(event.isCollect() ? 2 : 1);
				}
			}
			if (adapter != null) {
				adapter.notifyDataSetChanged();
			}
		}
	}
	
	@Subscribe
	public void onEventPlayStute(Boolean isPlaying){
		MusicPlayManager.getInstance(this).setPlaying(isPlaying);
		if (adapter != null) {
			adapter.notifyDataSetChanged();
		}
	}
	
	@Subscribe
	public void readBookNumChange(BookNumChangeEvent event){
		handle.obtainMessage(100, event.getBookId(), 0).sendToTarget();
	}
	
	public void registerEvent(){
//		EventBus.getEventBus(HttpRequestHelper.COLLECT_EVENT,ThreadEnforcer.MAIN).register(this);
		EventBus.getEventBus("m_play_stute" , ThreadEnforcer.MAIN).register(this);
		EventBus.getEventBus("readbook_num_change" , ThreadEnforcer.MAIN).register(this);
	}
	
	
	public void unRegisterEvent(){
//		EventBus.getEventBus(HttpRequestHelper.COLLECT_EVENT,ThreadEnforcer.MAIN).unregister(this);
		EventBus.getEventBus("m_play_stute" , ThreadEnforcer.MAIN).unregister(this);
		EventBus.getEventBus("readbook_num_change" , ThreadEnforcer.MAIN).unregister(this);
	}
	
	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		setIntent(intent);
		initView();
		getBookList();
	}
	
	/***
	 * 处理高斯模糊
	 */
	public void applyBlur() {
		image_render.getViewTreeObserver().addOnPreDrawListener(
				new ViewTreeObserver.OnPreDrawListener() {
					@Override
					public boolean onPreDraw() {
						if (time > 0) {
							time --;
						} else {
							image_render.getViewTreeObserver().removeOnPreDrawListener(this);
						}
						image_render.buildDrawingCache();
						Bitmap bmp = image_render.getDrawingCache();
						FastBlur.blur(bmp, view2, AnchorInfoActivity.this);
						return true;
					}
		});
	}
	
	public void getBookList(){
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair(HttpRequestHelper.USERID, String.valueOf(SharedPreferencesUtils.getParam(this, HttpRequestHelper.USERID, 0))));
		params.add(new BasicNameValuePair("anchorId", String.valueOf(anchorBean.getId())));
		params.add(new BasicNameValuePair(HttpRequestHelper.PAGE_INDEX, String.valueOf(pageIndex)));
		HttpRequestHelper.getGuessYouLike(this, HttpRequestHelper.ANCHOR_BOOK_LIST, params, handle, GETDATA_SUCCESS, GETDATA_FAIL);
	}

	@Override
	public boolean handleMessage(Message msg) {
		ShareOpUtils.handleShareCallBack(this, msg);
		return false;
	};
}
